//
// Created by liaohailong on 2025/4/20.
//

#ifndef HELLOVIDEOCACHE_HELLODOWNLOADER_HPP
#define HELLOVIDEOCACHE_HELLODOWNLOADER_HPP


#include "curl/curl.h"
#include <iostream>
#include <fstream>
#include <string>
#include <unordered_map>
#include <unistd.h> // write

#include "../cache/HelloCacheManager.hpp"
#include "../cache/HelloCacheInfo.hpp"
#include "../net/HelloHttpRequest.hpp"
#include "../log/Logger.hpp"

/**
 * create by liaohailong
 * 2025/4/20 13:05
 * desc: 使用 curl 下载文件
 */
class HelloDownloader
{
public:
    typedef struct
    {
        Logger *logger;
        std::shared_ptr<HelloCacheInfo> cacheInfo;
        int fd;
        std::string url;
        std::unordered_map<std::string, std::string> requestHeaders;
        std::string responseHeaderLines;
        bool sendHeader; // 是否需要回写header给客户端
        bool write2index; // 是否更新header到index文件
        std::shared_ptr<std::ofstream> ofs; // 缓存文件流
        std::shared_ptr<HelloRange> range;
    } HelloDownloadCtx;

public:
    HelloDownloader();

    ~HelloDownloader();

    std::shared_ptr<HelloDownloader::HelloDownloadCtx> newParams(
            const std::shared_ptr<HelloCacheManager> &cache,
            const std::shared_ptr<HelloHttpRequest> &request,
            const std::shared_ptr<HelloRange> &range
    );

    bool download(const std::shared_ptr<HelloDownloader::HelloDownloadCtx>& params);

    static size_t headerCallback(char *buffer, size_t size, size_t nitems, void *userdata);

    static size_t writeCallback(char *ptr, size_t size, size_t nmemb, void *userdata);

private:
    Logger logger;
};


#endif //HELLOVIDEOCACHE_HELLODOWNLOADER_HPP
